<template>
  <div>
    <div v-if="!reviewPage">
      <div v-if="type == '顺序练习'">
        历史正确率
        {{ selectedNum == 0 ? 0 : Math.round((rightNum / selectedNum) * 100) }}%
      </div>
      <div v-if="type != '顺序练习'">
        当前正确率
        {{ selectedNum == 0 ? 0 : Math.round((rightNum / selectedNum) * 100) }}%
      </div>
    </div>
    <div :key="item.id" :style="head_item">
      {{ index + 1 }}.{{ item.question }}
    </div>
    <div>
      <!-- 单选框 -->
      <van-radio-group v-model="selectedRatio" v-show="item.answer.length == 1">
        <div :style="selectd_item1">
          <van-radio name="A" :checked-color="checkColor" @click="radioHandler"
            ><div ref="radio_item1">{{ item.item1 }}</div></van-radio
          >
        </div>
        <div :style="selectd_item2">
          <van-radio name="B" :checked-color="checkColor" @click="radioHandler"
            ><div ref="radio_item2">{{ item.item2 }}</div></van-radio
          >
        </div>
        <div :style="selectd_item3">
          <van-radio name="C" :checked-color="checkColor" @click="radioHandler"
            ><div ref="radio_item3">{{ item.item3 }}</div></van-radio
          >
        </div>
        <div :style="selectd_item4" v-if="item.item4">
          <van-radio name="D" :checked-color="checkColor" @click="radioHandler"
            ><div ref="radio_item4">{{ item.item4 }}</div></van-radio
          >
        </div>
      </van-radio-group>
      <!-- 多选框 -->
      <van-checkbox-group
        v-model="selectedChecked"
        v-show="item.answer.length > 1"
      >
        <div :style="selectd_item1">
          <van-checkbox name="A" :checked-color="checkColor" shape="square"
            ><div ref="check_item1">{{ item.item1 }}</div></van-checkbox
          >
        </div>
        <div :style="selectd_item2">
          <van-checkbox name="B" :checked-color="checkColor" shape="square"
            ><div ref="check_item2">{{ item.item2 }}</div></van-checkbox
          >
        </div>
        <div :style="selectd_item3">
          <van-checkbox name="C" :checked-color="checkColor" shape="square"
            ><div ref="check_item3">{{ item.item3 }}</div></van-checkbox
          >
        </div>
        <div :style="selectd_item4" v-if="item.item4">
          <van-checkbox name="D" :checked-color="checkColor" shape="square"
            ><div ref="check_item4">{{ item.item4 }}</div></van-checkbox
          >
        </div>
      </van-checkbox-group>
      <div v-if="item.item4" class="confirm_item">
        <van-button
          icon="success"
          style="margin-top: 20px"
          type="info"
          v-show="item.answer.length > 1"
          @click="confirm"
          >确 定</van-button
        >
      </div>
    </div>
    <div :style="remark_item">
      <div v-show="item.remark && showRemark">答案解析：</div>
      <div v-show="showRemark">{{ item.remark }}</div>
    </div>
    <div class="func_item" ref="funcItem">
      <div class="func_item_left">
        <div class="func_item_button">
          <van-button
            type="info"
            icon="success"
            size="small"
            @click="showAnswer"
            >答 案</van-button
          >
        </div>
        <div class="func_item_button">
          <van-button
            :type="collectFlag ? 'primary' : 'info'"
            :icon="collectFlag ? 'like-o' : 'star-o'"
            size="small"
            @click="collect"
            >收 藏</van-button
          >
        </div>
      </div>
      <div class="picker_box">
        <!-- {{ index + 1 }}/{{ total }} -->
        <!-- <div class="picker_box1">
          <van-field v-model="digit" type="digit" label="整数" />
          <div class="picker_box1_input"><input v-model="digit" style="height: 30px; width: 60px;" type="number"></input></div>
        </div>
        <div v-if="total>0" class="picker_box2"><div class="picker_box2_input">跳转</div>共{{ total }}题</div> -->
        <div>
          <input
            v-model="nowIndex"
            style="height: 32px; width: 40px; font-size: 10px"
            type="number"
          />
        </div>
        <div class="picker_box2">
          <div class="picker_box2_1" @click="skip">跳转</div>
          <div class="picker_box2_2" v-if="total > 0">共{{ total }}题</div>
        </div>
      </div>
      <div class="func_item_right">
        <div class="func_item_button">
          <van-button type="info" icon="arrow-left" size="small" @click="prev"
            >上一题</van-button
          >
        </div>
        <div class="func_item_button">
          <van-button type="info" icon="arrow" size="small" @click="next"
            >下一题</van-button
          >
        </div>
      </div>
    </div>
    <!-- <van-popup v-model="show" position="bottom"
      ><van-picker
        title="选择题目"
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="onCancel"
        @change="onChange"
    /></van-popup> -->
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import questionItem from "@/api/questionItem/questionItem";
import collectRecord from "@/api/record/collectRecord";
import userRecord from "@/api/record/userRecord";
import selectRecord from "@/api/record/selectRecord";
import wrongRecord from "@/api/record/wrongRecord";
import selfTest from "@/api/selfTest";
import selfTestAnswer from "@/api/selfTest/selfTestAnswer";
import { Notify } from "vant";
import { Dialog } from "vant";
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      nowIndex: 1, //用于跳转的页面索引
      reviewPage: false, //是否是回顾试卷的页面，默认不是，但是当从回顾试卷页面点击某道题进来的时候，该属性会变成true
      headHeight: 60, //题目区的高度
      remarkHeight: 200, //答案解析区的高度
      heigth1: 40,
      heigth2: 40,
      heigth3: 40,
      heigth4: 40,
      wrongItems: [], //做错的题目
      checkColor: "#1989fa",
      recordedAns: [],
      showAnswerFlag: false, //当点击查看答案后，此变成了true，不会增加正确率
      showRemark: false, //控制解析是否显示，当回答正确以后，会显示解析
      confirmFlag: false, //当点击了确认键后，该flag会变成true
      type: "顺序练习", //练习的类型，现在支持的有顺序练习，随机练习，收藏练习，错题练习
      selectedId: 1, //用户选择的类型
      columns: [],
      //show: false, //用于控制下拉选择器是否显示
      index: 0,
      total: 0,
      items: [], //所有的题
      item: {
        subject: "",
        question: "",
        item1: "",
        item2: "",
        item3: "",
        item4: "",
        answer: "",
        remark: "",
      }, //单独的某一道题
      selectedRatio: "", //选择单选题的答案
      selectedChecked: [], //选择多选题的答案
      collectFlag: false, //表示该题目是否被收藏过
      rightNum: 0, //做对的题目的数量
      selectedNum: 0, //已选择的题目的数量
    };
  },
  /* .selectd_item {
display: flex;
align-items: center;
height: 40px;
margin-top: 22px;
} */
  //计算属性 类似于 data 概念
  computed: {
    head_item() {
      return {
        "margin-top": "20px",
        height: `${this.headHeight}px`,
        overflow: "auto",
      };
    },
    remark_item() {
      return {
        height: `${this.remarkHeight}px`,
        "margin-top": "20px",
        overflow: "auto" /* 隐藏溢出部分 */,
      };
    },
    selectd_item1() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth1}px`,
      };
    },
    selectd_item2() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth2}px`,
      };
    },
    selectd_item3() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth3}px`,
      };
    },
    selectd_item4() {
      return {
        display: "flex",
        "align-items": "center",
        height: `${this.heigth4}px`,
      };
    },
  },
  //监控 data 中的数据变化
  watch: {
    /**
     * 当用户切换题目时，会记录以下信息
     * 1.检查用户是否收藏过该题
     * 2.查找关于该题用户是否以前做过，如果以前做过，则查找曾经的记录
     * 3.将上一道题的用户的记录记录到数据库中
     * 3.统计正确率（todo）
     * @param {用户点击上下题目或者切换题目时，index会发生改变} newVal
     */
    index(newVal, oldVal) {
      this.nowIndex = newVal + 1;
      this.setDefault();
      this.countAccuracy(newVal, oldVal);
      // this.selectedRatio = "";
      // this.selectedChecked = [];
      this.recordSelected(oldVal);
      this.reviewSelected(newVal);
      //这里不管是顺序练习还是错题练习还是随机练习，都会记录做题记录，但是只有顺序练习会把做题记录上传
      // if (this.type == "顺序练习") {
      //   this.recordSelected(oldVal);
      //   this.reviewSelected(newVal);
      // } else {
      //   this.selectedRatio = "";
      //   this.selectedChecked = [];
      // }
      this.item = this.items[newVal];
      this.checkCollect();
      this.confirmFlag = false;
      this.showRemark = false;
      this.showAnswerFlag = false;
      // this.remarkHeight = 0;
      this.calculateTextLines();
      this.sentToServer();
    },
    selectedRatio(newVal) {
      if (newVal != "") {
        if (newVal == this.item.answer) {
          this.setRight();
        } else {
          this.setWrong();
        }
      }
    },
    selectedChecked(newVal) {
      if (newVal.length != 0) {
        //由于这是多选框，必须要用户点击确定才会显示正确答案，
        //为了防止用户点击时也会显示，这里判断一下
        //只有存储的this.recordedAns选项记录里有记录，也就是说是用户回顾题目时才会改变div的颜色
        if (
          this.recordedAns[this.index] != ["", "", "", ""] &&
          !this.confirmFlag
        ) {
          let arr = this.recordedAns[this.index].filter((a) => a != "");
          let selectedChecked = "";
          for (let index = 0; index < arr.length; index++) {
            const element = arr[index];
            selectedChecked += element;
            if (index < arr.length - 1) {
              selectedChecked += "+";
            }
          }
          this.setDefault();
          if (selectedChecked == this.item.answer) {
            this.setRight();
          } else {
            this.setWrong();
          }
        }
      }
    },
  },
  //方法集合
  methods: {
    skip() {
      if (this.nowIndex < 1) {
        Notify({ type: "danger", message: "跳转页码不合法！" });
        return;
      }
      if (this.nowIndex > this.total) {
        Notify({ type: "danger", message: "跳转页码不合法！" });
        return;
      }
      this.index = parseInt(this.nowIndex) - 1;
    },
    /**
     * 每次题目切换时，都会记录
     * 1.顺序练习时的记录和做到第几道题了
     * 2.如果是错题练习，则清除错题
     * 3.如果非错题练习，则记录错题
     */
    sentToServer() {
      /*
    如果是顺序练习
    1.退出界面之前记录下本次练习到哪一道题了，方便下次来直接刷
    2.记录下用户每一道题的选项
    3.记录错题记录
    */
      if (this.type == "顺序练习") {
        userRecord.updateOrAdd(
          this.index,
          this.selectedId,
          this.rightNum,
          this.selectedNum
        );
        const jsonStr = JSON.stringify(this.recordedAns);
        selectRecord.updateOrAdd(jsonStr, this.selectedId);
      }
      if (this.type != "错题练习") {
        wrongRecord.addOrUpdate(this.wrongItems, this.selectedId);
      } else {
        //这里如果做到最后一道题的时候无法消除错题，为了解决这个问题，在做到最后一道题的时候人为消除错题
        if (this.index == this.total - 1) {
          let selected =
            this.selectedChecked.length == 0
              ? this.selectedRatio
              : this.selectedChecked;
          let arrToStr = "";
          if (selected.length > 1) {
            selected = selected.sort();
            for (let i = 0; i < selected.length; i++) {
              const element = selected[i];
              arrToStr += element;
              if (i < selected.length - 1) {
                arrToStr += "+";
              }
            }
          } else {
            arrToStr = selected[0];
          }
          if (arrToStr == this.item.answer) {
            wrongRecord.deleteByQuestionId(this.item.id);
          }
        }
      }
      // this.recordedAns = [];
    },
    /**
     * 计算单选框，复选框的文字的高度
     */
    calculateTextLines() {
      //如果有选项4为非英语M9
      if (this.item.item4) {
        let van1;
        let van2;
        let van3;
        let van4;
        this.$nextTick(() => {
          if (this.item.answer.length > 1) {
            van1 = this.$refs.check_item1;
            van2 = this.$refs.check_item2;
            van3 = this.$refs.check_item3;
            van4 = this.$refs.check_item4;
          } else {
            van1 = this.$refs.radio_item1;
            van2 = this.$refs.radio_item2;
            van3 = this.$refs.radio_item3;
            van4 = this.$refs.radio_item4;
          }
          //这里为了美观，在刚进入页面时，如果选择框的高度为0，也就是第一次进入页面时，此时由于其高度为0，给他一个默认高度40
          this.heigth1 =
            van1.clientHeight == 0
              ? van1.clientHeight + 40
              : van1.clientHeight + 20;
          this.heigth2 =
            van2.clientHeight == 0
              ? van2.clientHeight + 40
              : van2.clientHeight + 20;
          this.heigth3 =
            van3.clientHeight == 0
              ? van3.clientHeight + 40
              : van3.clientHeight + 20;
          this.heigth4 =
            van4.clientHeight == 0
              ? van4.clientHeight + 40
              : van4.clientHeight + 20;

          if (this.item.item4) {
            this.remarkHeight =
              360 - (this.heigth1 + this.heigth2 + this.heigth3 + this.heigth4);
          } else {
            this.remarkHeight =
              260 - (this.heigth1 + this.heigth2 + this.heigth3 + this.heigth4);
          }
        });
      } else {
        //如果无选项4为英语M9
        let van1;
        let van2;
        let van3;
        this.$nextTick(() => {
          if (this.item.answer.length > 1) {
            van1 = this.$refs.check_item1;
            van2 = this.$refs.check_item2;
            van3 = this.$refs.check_item3;
          } else {
            van1 = this.$refs.radio_item1;
            van2 = this.$refs.radio_item2;
            van3 = this.$refs.radio_item3;
          }
          //这里为了美观，在刚进入页面时，如果选择框的高度为0，也就是第一次进入页面时，此时由于其高度为0，给他一个默认高度40
          this.heigth1 =
            van1.clientHeight == 0
              ? van1.clientHeight + 80
              : van1.clientHeight + 20;
          this.heigth2 =
            van2.clientHeight == 0
              ? van2.clientHeight + 80
              : van2.clientHeight + 20;
          this.heigth3 =
            van3.clientHeight == 0
              ? van3.clientHeight + 80
              : van3.clientHeight + 20;
          if (this.item.item4) {
            this.remarkHeight =
              360 - (this.heigth1 + this.heigth2 + this.heigth3 + this.heigth4);
          } else {
            this.remarkHeight =
              260 - (this.heigth1 + this.heigth2 + this.heigth3 + this.heigth4);
          }
        });
      }
    },
    /**
     * 重置recordedAns数组，此方法只有在recordedAns数组发生错误时调用
     */
    resetRecordAns() {
      for (let index = 0; index < this.total; index++) {
        let arr = [];
        for (let i = 0; i < 4; i++) {
          arr.push("");
        }
        this.recordedAns.push(arr);
      }
      this.rightNum = 0;
      this.selectedNum = 0;
    },
    /**
     * 统计正确率
     * 1.如果之前做过该题了，那么正确率不会改变
     * 2.通过查看this.recordedAns[oldVal]是否全为空看这道题是否做过了
     */
    countAccuracy(newVal, oldVal) {
      if (this.recordedAns.length == 0) {
        Dialog.confirm({
          title: "系统发生错误",
          message: "您的组件recordedAns元件为空数组，是否为您清空做题记录?",
        })
          .then(() => {
            // on confirm
            this.resetRecordAns();
          })
          .catch(() => {
            // on cancel
          });
      }
      let arr = this.recordedAns[oldVal].filter((a) => a != "");
      if (arr.length == 0) {
        if (this.confirmFlag == true || this.selectedRatio != "") {
          let myAnswer =
            this.selectedChecked.length != 0
              ? this.selectedChecked
              : this.selectedRatio;
          let arrToStr = "";
          if (myAnswer.length > 1) {
            myAnswer = myAnswer.sort();
            for (let index = 0; index < myAnswer.length; index++) {
              const element = myAnswer[index];
              arrToStr += element;
              if (index < myAnswer.length - 1) {
                arrToStr += "+";
              }
            }
          } else {
            arrToStr = myAnswer[0];
          }
          myAnswer = arrToStr;
          //只有当答案正确且不是用户点击查看答案作对的才能增加正确率
          this.selectedNum++;
          if (myAnswer == this.item.answer && !this.showAnswerFlag) {
            this.rightNum++;
            if (this.type == "错题练习") {
              wrongRecord.deleteByQuestionId(this.item.id);
            }
          } else {
            this.wrongItems.push(this.item.id);
          }
        }
      }
    },
    /**
     * 将选项的背景色设置为默认颜色
     */
    setDefault() {
      this.checkColor = "1989fa";
    },
    /**
     * 当用户选择错误时，渲染错误的选项的背景
     * 在这里记录错题
     */
    setWrong() {
      this.checkColor = "red";
    },
    /**
     * 当用户选择正确时，渲染正确的选项的背景
     */
    setRight() {
      this.checkColor = "green";
    },
    /**
     * 查找关于该题用户是否以前做过，如果以前做过，则查找曾经的记录
     * 即，恢复该题的选项
     */
    reviewSelected(newVal) {
      let res = this.recordedAns[newVal].filter((a) => a != "");
      if (res.length > 1) {
        this.selectedChecked = res;
      }
      if (res.length == 1) {
        this.selectedRatio = res[0];
      }
    },
    /**
     * 将上一道题的用户的记录记录到数据库中
     */
    recordSelected(oldVal) {
      // console.log(
      //   "recordSelected",
      //   this.recordedAns[oldVal],
      //   oldVal,
      //   this.selectedChecked
      // );
      if (
        (this.selectedChecked.length != 0 && this.confirmFlag) ||
        this.selectedRatio != ""
      ) {
        for (let index = 0; index < 4; index++) {
          this.recordedAns[oldVal][index] = "";
        }
        //只要在切换题目之前用户有做过记录，就将其记录
        if (this.selectedChecked.length != 0) {
          //多选题
          for (let index = 0; index < this.selectedChecked.length; index++) {
            const element = this.selectedChecked[index];
            this.pushToRecordAns(element, oldVal);
          }
        } else {
          //单选题
          this.pushToRecordAns(this.selectedRatio, oldVal);
        }
      }
      this.selectedRatio = "";
      this.selectedChecked = [];
    },
    /**
     * 将用户选项存放到pushToRecordAns中
     * @param {A或B或C或D选项} selected
     */
    pushToRecordAns(selected, oldVal) {
      switch (selected) {
        case "A":
          this.recordedAns[oldVal][0] = selected;
          break;
        case "B":
          this.recordedAns[oldVal][1] = selected;
          break;
        case "C":
          this.recordedAns[oldVal][2] = selected;
          break;
        default:
          this.recordedAns[oldVal][3] = selected;
          break;
      }
    },
    /**
     * 检查该题有没有被收藏过
     */
    checkCollect() {
      collectRecord.checkCollect(this.item.id).then((res) => {
        if (res.data == "收藏过") {
          this.collectFlag = true;
        } else {
          this.collectFlag = false;
        }
      });
    },
    /**
     * 显示正确答案
     */
    showAnswer() {
      this.showAnswerFlag = true;
      if (this.item.answer.length == 1) {
        this.selectedRatio = this.item.answer;
      } else {
        let arr = this.item.answer.split("+");
        this.selectedChecked = arr;
      }
    },
    /**
     * 收藏该题
     */
    collect() {
      this.collectFlag = !this.collectFlag;
      let collectFlag = this.collectFlag ? 1 : 0;
      collectRecord.updateCollect(this.item.id, collectFlag);
    },
    next() {
      if (this.index == this.total - 1) {
        this.$message({
          message: "已经是最后一题了！",
          type: "error",
        });
        return;
      }
      this.index = this.index + 1;
    },
    prev() {
      if (this.index == 0) {
        this.$message({
          message: "已经是第一题了！",
          type: "error",
        });
        return;
      }
      this.index = this.index - 1;
    },
    /**
     * 比较选择的答案和正确答案是否一样
     * @param {选择的答案} selected
     * @param {正确答案} answer
     */
    checkAnswer(selected) {
      if (selected == this.item.answer) {
        Notify({
          type: "success",
          message: "回答正确!",
          duration: 1500,
        });
        this.showRemark = true;
      } else {
        Notify({ type: "danger", message: "回答错误!", duration: 1500 });
      }
    },
    /**
     * 单选题点击完即显示正确与否，当回答正确以后，如果有解析则自动显示解析
     */
    radioHandler() {
      //比较是否正确
      this.checkAnswer(this.selectedRatio);
    },
    /**
     * 多选题点击完成后需要再点击一个确认才能显示是否正确
     */
    confirm() {
      if (this.selectedChecked.length == 0) {
        Notify({ type: "warning", message: "请选择您的选项!" });
        return;
      }
      this.confirmFlag = true;
      //先把选好的答案排个序
      let arr = this.selectedChecked.sort();
      let selectedChecked = "";
      for (let index = 0; index < arr.length; index++) {
        const element = arr[index];
        selectedChecked += element;
        if (index < arr.length - 1) {
          selectedChecked += "+";
        }
      }
      this.setDefault();
      if (selectedChecked == this.item.answer) {
        this.setRight();
      } else {
        this.setWrong();
      }
      this.checkAnswer(selectedChecked);
    },
    // onConfirm(value, index) {
    //   this.index = index;
    //   this.show = false;
    // },
    // onCancel() {
    //   this.show = false;
    // },
    // onChange(picker, value, index) {
    //   this.index = index;
    //   this.item = this.items[this.index];
    //   this.show = false;
    // },
    // showPopup() {
    //   this.show = true;
    // },
    returnToIndex(notify) {
      Notify({
        type: "danger",
        message: notify,
      });
      this.$router.push({
        path: "/learn/index",
      });
    },
    /**
     * 初始化recordAns，这里只是简单的初始化，并不会向recordAns里填充记录
     */
    initRecordsAns() {
      for (let index = 0; index < this.total; index++) {
        let arr = [];
        for (let i = 0; i < 4; i++) {
          arr.push("");
        }
        this.recordedAns.push(arr);
      }
    },
    /**
     * 初始化items
     */
    initItems(res) {
      this.items = res.data;
      this.item = this.items[0];
      this.total = this.items.length;
      for (let index = 0; index < this.items.length; index++) {
        const element = this.items[index];
        let column = index + 1 + "." + element.question;
        this.columns.push(column);
      }
      this.total = this.columns.length;
      //如果选项4是空字符串，表示是英语阅读
      if (!this.item.item4) {
        this.headHeight = 150;
      }
    },
    /**
     * 当页面创建完成后，从数据库中获取题库
     * 系统有两种办法可以进入该页面
     * 1.通过点击顺序练习，随机练习等按钮
     * 2.通过搜索题目，当搜索题目进来的时候，里面的功能等同于随机练习
     * 3.目前进入该页面的方式有
     * 3.1点击顺序练习或者收藏练习等方式
     * 3.2搜索题目进入
     * 3.3通过回顾错题进入
     */
    getQuestions: async function () {
      //如果路径里有question参数表示是通过回顾错题进入该页面
      if (
        this.$route.query.type == "随机练习" &&
        this.$route.query.question != undefined
      ) {
        this.type = this.$route.query.type;
        const res = await questionItem.getLearnItemsByQuestion(
          this.$route.query.question
        );
        if (res.data.length == 0) {
          this.returnToIndex("搜索无结果！");
          return;
        }
        this.initItems(res);
        this.initRecordsAns();
        this.checkCollect();
      } else if (
        //如果路径里有selfTestId参数表示是通过回顾错题进入该页面，这里页面的操作逻辑和随机练习一致
        //不会记录错题和做题记录
        this.$route.query.selfTestId != undefined &&
        this.$route.query.type == "回顾错题"
      ) {
        this.type == "随机练习";
        this.reviewPage = true;
        const res = await selfTest.geBySelfTestId(this.$route.query.selfTestId);
        this.initItems(res);
        this.initSelfRecord();
        this.checkCollect();
      } else if (
        //如果路径里有selectedId参数表示是点击顺序练习或者收藏练习等方式进入该页面
        this.$route.query.selectedId != undefined &&
        this.$route.query.type != undefined
      ) {
        this.selectedId = this.$route.query.selectedId;
        this.type = this.$route.query.type;
        const res = await questionItem.getLearnItems(
          this.$route.query.type,
          this.$route.query.selectedId
        );
        if (res.data.length == 0) {
          if (this.type == "错题练习") {
            this.returnToIndex("您没有错题！请继续保持！");
            return;
          }
          if (this.type == "收藏练习") {
            this.returnToIndex("您没有收藏任何题目！");
            return;
          }
        }
        this.initItems(res);
        if (this.type == "顺序练习") {
          this.getRecord();
        } else {
          this.initRecordsAns();
        }
        this.checkCollect();
      } else {
        this.$router.push({
          path: `/learn/index`,
        });
        return;
      }
      //如果index是0的话，由于很多逻辑都是在watch里观察index的变化的，如果index在一进入页面就是0，则无法触发，因此需要人工触发
      if (this.index == 0) {
        this.calculateTextLines();
      }
    },
    /**
     * 重置刷题记录
     */
    reset() {
      Dialog.confirm({
        message: "重新来过会清空您该章节的所有记录，是否确认？",
        cancelButtonColor: "green",
      })
        .then(() => {
          userRecord.deleteBySelectId(this.selectedId).then((response) => {
            Notify({ type: "success", message: `${response.data}` });
            for (let index = 0; index < this.total; index++) {
              let arr = [];
              for (let i = 0; i < 4; i++) {
                arr.push("");
              }
              this.recordedAns.push(arr);
            }
          });
        })
        .catch(() => {
          this.rightNum = res.data.rightNum;
          this.selectedNum = res.data.selectedNum;
          this.initRecords(res.data.indexRecord);
        });
    },
    resetConfirm(res) {
      Dialog.confirm({
        message: `您上一次练习到第${res.data.indexRecord + 1}题，是否继续？`,
        confirmButtonText: "继续练习",
        cancelButtonText: "重新来过",
        cancelButtonColor: "red",
        confirmButtonColor: "green",
      })
        .then(() => {
          this.rightNum = res.data.rightNum;
          this.selectedNum = res.data.selectedNum;
          this.initRecords(res.data.indexRecord);
        })
        .catch(() => {
          this.reset();
        });
    },
    initSelfRecord() {
      selfTestAnswer
        .geBySelfTestId(this.$route.query.selfTestId)
        .then((res) => {
          this.recordedAns = res.data;
          this.reviewSelected(0);
        });
    },
    /**
     * 页面创建完成后，从数据库中获取上一次学习的记录，方便从上次做的题目开始继续学习
     * 这里需要获取的记录有
     * 1.上次刷到第几题了
     * 2.上次做的正确率，即做对的题目和做的总题目
     */
    getRecord() {
      userRecord.getBySelectId(this.selectedId).then((res) => {
        if (res.data) {
          //此时给用户弹窗，用户可以选择接着之前的记录练习，也可以选择清空记录
          this.resetConfirm(res);
        } else {
          for (let index = 0; index < this.total; index++) {
            let arr = [];
            for (let i = 0; i < 4; i++) {
              arr.push("");
            }
            this.recordedAns.push(arr);
          }
        }
      });
    },
    /**
     * 从数据库获取用户之前做过的题目的选项
     * 更新做到第几道题了，即index
     */
    initRecords(param) {
      selectRecord.getBySelectId(this.selectedId).then((res) => {
        if (!res.data) {
          for (let index = 0; index < this.total; index++) {
            let arr = [];
            for (let i = 0; i < 4; i++) {
              arr.push("");
            }
            this.recordedAns.push(arr);
          }
        } else {
          //如果数据库里村的选项的长度不等于现在的总题目数代表新增了题目
          if (res.data.length != this.total) {
            //这里的策略就是如果新增了题目，因为都是在题目的末尾新增题目，
            //所以在 this.recordedAns的末尾新增this.total - res.data.length的长度的空数组就行
            let arr = JSON.parse(res.data.result.selected);
            for (let index = 0; index < this.total - res.data.length; index++) {
              let emptyArr = [];
              for (let i = 0; i < 4; i++) {
                emptyArr.push("");
              }
              arr.push(emptyArr);
            }
            this.recordedAns = arr;
          } else {
            this.recordedAns = JSON.parse(res.data.result.selected);
          }
        }
        this.index = param;
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.getQuestions();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped>
/* .head_item {
  margin-top: 20px;
  height: 60px;
  overflow: auto;
} */
.confirm_item {
  height: 65px;
}
/* .selectd_item {
display: flex;
align-items: center;
height: 40px;
margin-top: 22px;
} */
/* .remark_item { */
/* height: 200px; */
/* margin-top: 20px; */
/* overflow: auto;  */
/* 隐藏溢出部分 */
/* } */

.func_item {
  margin-top: 5px;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
}
.picker_box {
  display: flex;
  justify-content: left;
  height: 32px;
  /* background-color: rgb(191, 203, 203); */
  border-radius: 2px;
  width: 30%;
  margin-right: 2px;
  margin-left: 2px;
  text-align: center; /* 水平居中对齐 */
  font-size: 20px; /* 字体大小 */
}

.picker_box2 {
  width: 78px;
}
.picker_box2_1 {
  font-size: 14px;
  color: white;
  margin-left: 2px;
  background-color: #5599ff;
  border-radius: 2px;
}
.picker_box2_2 {
  font-size: 12px;
  margin-left: 2px;
}
.func_item_left {
  width: 29%;
  display: flex;
  justify-content: left;
}
.func_item_right {
  width: 39%;
  display: flex;
  justify-content: right;
}
.func_item_button {
  margin-left: 1px;
  margin-right: 1px;
}
</style>